/**
 * 
 */
package com.example.radioclub.music.tasks;

import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import com.example.radioclub.data.Constants;
import com.example.radioclub.music.helper.ClientRequestFactory;
import com.example.radioclub.music.interfaces.IRestMusic;

import android.os.AsyncTask;
import android.util.Log;

/**
 * This task is used to authenticate client and in this case application.
 * 
 * @author wizard
 * 
 */
public class RestClientAuthDownloader extends AsyncTask<Void, Void, Object[]> {
	private final String TAG = Constants.APP_TAG + "Rest Auth Downloader";
	private String username, password;
	private RestTemplate mapiEmptyRestTemplate;
	private MultiValueMap<String, String> map = null;
	private IRestMusic listener;

	public RestClientAuthDownloader(String username, String password, IRestMusic listener) {
		this.username = username;
		this.password = password;
		this.mapiEmptyRestTemplate = new RestTemplate(true);
		this.map = new LinkedMultiValueMap<String, String>();
		this.listener = listener;
	}

	@Override
	protected Object[] doInBackground(Void... params) {
		// TODO Auto-generated method stub
		this.map.add("clientName", this.username);
		this.map.add("password", this.password);
		try {
			String result = this.mapiEmptyRestTemplate.postForObject(
					Constants.API_MELON_AUTH_CLIENT, this.map, String.class);
			ResponseEntity<String> response = this.mapiEmptyRestTemplate
					.postForEntity(Constants.API_MELON_AUTH_CLIENT, this.map,
							String.class, this.map);
			String cookie = response.getHeaders().get("Set-Cookie") + "";
			if (cookie != null) {
				return new Object[] {
						new RestTemplate(true, new ClientRequestFactory("Cookie", cookie)),
						new JSONObject(response.getBody()).getString("channelCd"),
						new String(cookie) 
					};
			}
		} catch (ResourceAccessException e) {
			e.printStackTrace();
			Log.i(TAG, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			Log.i(TAG, e.getMessage());
		}
		return null;
	}

	@Override
	protected void onPostExecute(Object[] result) {
		// TODO Auto-generated method stub
		this.listener.onClientAuthenticationFinished(result);
	}
}
